<template>
	<view class="category-container">
		<!-- 顶部标题栏 -->
		<view class="page-header">
			<text class="page-title">分类</text>
		</view>
		
		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- 左侧分类列表 -->
			<scroll-view class="category-sidebar" scroll-y="true">
				<!-- 推荐分类 -->
				<view
					class="category-item"
					:class="{ 'category-active': selectedCategoryId === 'recommend' }"
					@click="selectCategory('recommend')"
				>
					<text class="category-name">推荐</text>
				</view>

				<!-- 一级分类列表 -->
				<view
					v-for="(category, index) in categories"
					:key="category.id"
					class="category-item"
					:class="{ 'category-active': selectedCategoryId === category.id }"
					@click="selectCategory(category.id)"
				>
					<text class="category-name">{{ category.name }}</text>
				</view>
			</scroll-view>

			<!-- 右侧内容区域 -->
			<scroll-view class="content-area" scroll-y="true">
				<!-- 顶部横幅 -->
				<view class="content-header">
					<view class="category-banner" @click="onBannerClick">
						<image 
							class="banner-image" 
							src="/static/images/category-banner.svg" 
							mode="aspectFill"
							@error="onBannerImageError"
						/>
						<view class="banner-overlay">
							<text class="banner-title">海关商品分类</text>
							<text class="banner-subtitle">精选优质进口商品</text>
						</view>
					</view>
				</view>
				
				<!-- 加载状态 -->
				<view v-if="isLoading" class="loading-container">
					<view class="loading-spinner"></view>
					<text class="loading-text">加载中...</text>
				</view>

				<!-- 推荐内容 -->
				<view v-else-if="selectedCategoryId === 'recommend'" class="recommend-content">
					<!-- 推荐商品网格 -->
					<view class="sub-category-grid">
						<view
							v-for="(item, index) in recommendSubCategories"
							:key="index"
							class="sub-category-item"
							@click="goToSubCategory(item)"
						>
							<view class="sub-category-icon">
								<image
									v-if="item.icon"
									class="category-image"
									:src="getImageUrl(item.icon)"
									mode="aspectFit"
									@error="handleImageError"
								/>
								<text v-else class="icon-placeholder">✉</text>
							</view>
							<text class="sub-category-name">{{ item.name || '二级分类' }}</text>
						</view>
					</view>
				</view>

				<!-- 分类内容 -->
				<view v-else class="category-content">
					<!-- 二级分类网格 -->
					<view v-if="subCategories.length > 0" class="sub-category-grid">
						<view
							v-for="(subCategory, index) in subCategories"
							:key="subCategory.id"
							class="sub-category-item"
							@click="goToSubCategory(subCategory)"
						>
							<view class="sub-category-icon">
								<image
									v-if="subCategory.icon"
									class="category-image"
									:src="getImageUrl(subCategory.icon)"
									mode="aspectFit"
									@error="handleImageError"
								/>
								<text v-else class="icon-placeholder">✉</text>
							</view>
							<text class="sub-category-name">{{ subCategory.name || '二级分类' }}</text>
						</view>
					</view>

					<!-- 空状态 -->
					<view v-else class="empty-state">
						<!-- 生成一些占位的二级分类 -->
						<view class="sub-category-grid">
							<view v-for="i in 12" :key="i" class="sub-category-item placeholder-item">
								<view class="sub-category-icon">
									<text class="icon-placeholder">✉</text>
								</view>
								<text class="sub-category-name">二级分类</text>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import productApi from '../../api/product.js'

// 响应式数据
const categories = ref([])
const subCategories = ref([])
const selectedCategoryId = ref('recommend')
const isLoading = ref(false)

// 推荐商品数据（从API获取）
const recommendSubCategories = ref([])

// 页面加载
onMounted(() => {
	loadCategories()
	// 默认加载推荐商品数据
	loadRecommendProducts()
})

// 监听分类变化
watch(selectedCategoryId, (newCategoryId) => {
	console.log('分类变化:', newCategoryId)
	if (newCategoryId === 'recommend') {
		// 加载推荐商品数据
		loadRecommendProducts()
	} else if (newCategoryId) {
		// 加载对应的二级分类
		loadSubCategories()
	} else {
		// 清空二级分类
		subCategories.value = []
	}
})

// 加载分类列表
const loadCategories = async () => {
	try {
		console.log('开始加载一级分类列表...')
		isLoading.value = true

		const response = await productApi.getCategoryLevel1()
		console.log('一级分类列表响应:', response)

		if (response && Array.isArray(response)) {
			// 将后端返回的数据格式转换为前端需要的格式
			categories.value = response
				.filter(item => item.status === 1) // 只显示启用的分类
				.map(item => ({
					id: item.level1Id,
					name: item.name,
					sortOrder: item.sortOrder
				}))
				.sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0)) // 按排序字段排序

			console.log('处理后的分类数据:', categories.value)
		} else {
			console.warn('一级分类数据格式异常:', response)
			categories.value = []
		}
	} catch (error) {
		console.error('加载一级分类失败:', error)
		console.error('错误详情:', error.message)

		// 显示错误提示
		uni.showToast({
			title: '加载分类失败',
			icon: 'none',
			duration: 2000
		})

		// 使用空数组作为备用
		categories.value = []
	} finally {
		isLoading.value = false
	}
}

// 加载子分类
const loadSubCategories = async () => {
	try {
		console.log('开始加载二级分类列表，一级分类ID:', selectedCategoryId.value)

		const response = await productApi.getCategoryLevel2(selectedCategoryId.value)
		console.log('二级分类列表响应:', response)

		if (response && Array.isArray(response)) {
			// 将后端返回的数据格式转换为前端需要的格式
			subCategories.value = response
				.filter(item => item.status === 1) // 只显示启用的分类
				.map(item => ({
					id: item.level2Id,
					name: item.name,
					icon: item.icon,
					sortOrder: item.sortOrder
				}))
				.sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0)) // 按排序字段排序

			console.log('处理后的二级分类数据:', subCategories.value)
		} else {
			console.warn('二级分类数据格式异常:', response)
			subCategories.value = []
		}
	} catch (error) {
		console.error('加载二级分类失败:', error)
		console.error('错误详情:', error.message)

		// 显示错误提示
		uni.showToast({
			title: '加载子分类失败',
			icon: 'none',
			duration: 2000
		})

		// 使用空数组作为备用
		subCategories.value = []
	}
}

// 加载推荐商品
const loadRecommendProducts = async () => {
	try {

		const response = await productApi.getProduct()

		if (response && Array.isArray(response)) {
			// 将推荐商品数据转换为显示格式
			recommendSubCategories.value = response.map(item => {

				const imageUrl = getFirstImage(item.pic || item.image || item.images || item.icon || item.thumbnail)

				return {
					id: item.productId || item.id,
					name: item.name || item.productName,
					icon: imageUrl,
					price: item.price,
					originalPrice: item.originalPrice,
					salesCount: item.salesCount,
					avgScore: item.avgScore
				}
			})

		} else if (response && typeof response === 'object') {
			// 如果返回的是对象格式，尝试获取list字段
			const list = response.list || response.data || []
			if (Array.isArray(list)) {
				recommendSubCategories.value = list.map(item => ({
					id: item.productId || item.id,
					name: item.name || item.productName,
					icon: getFirstImage(item.pic || item.image || item.images || item.icon || item.thumbnail),
					price: item.price,
					originalPrice: item.originalPrice,
					salesCount: item.salesCount,
					avgScore: item.avgScore
				}))
			} else {
				recommendSubCategories.value = []
			}
		} else {
			recommendSubCategories.value = []
		}
	} catch (error) {

		// 显示错误提示
		uni.showToast({
			title: '加载推荐商品失败',
			icon: 'none',
			duration: 2000
		})

		// 使用空数组作为备用
		recommendSubCategories.value = []
	}
}

// 分类选择
const selectCategory = (categoryId) => {
	if (selectedCategoryId.value !== categoryId) {
		selectedCategoryId.value = categoryId
	}
}

// 跳转到子分类或商品详情
const goToSubCategory = (item) => {

	// 如果是推荐页面，跳转到商品详情
	if (selectedCategoryId.value === 'recommend') {
		uni.navigateTo({
			url: `/pages/product/detail?productId=${item.id}`
		})
	} else {
		// 如果是分类页面，跳转到商品列表页面
		uni.navigateTo({
			url: `/pages/category/list?categoryId=${item.id}&categoryName=${encodeURIComponent(item.name)}`
		})
	}
}

// 处理图片数据，支持数组、逗号分隔字符串等格式
const getFirstImage = (imageData) => {

	if (!imageData) {
		console.log('图片数据为空')
		return ''
	}

	// 如果是数组，取第一个元素
	if (Array.isArray(imageData)) {
		const firstImage = imageData[0]
		return firstImage || ''
	}

	// 如果是字符串，可能是逗号分隔的
	if (typeof imageData === 'string') {
		const firstImage = imageData.split(',')[0].trim()
		return firstImage
	}

	return ''
}

// 处理图片URL
const getImageUrl = (iconPath) => {

	if (!iconPath) {
		console.log('❌ 图片路径为空')
		return ''
	}

	// 如果是完整的URL，直接返回
	if (iconPath.startsWith('http://') || iconPath.startsWith('https://')) {
		console.log('✅ 完整URL，直接返回:', iconPath)
		return iconPath
	}

	// 如果是相对路径，需要拼接基础URL
	if (iconPath.startsWith('/')) {
		// 从环境变量或配置中获取图片服务器地址
		const baseImageUrl = 'http://8.145.55.161:19000' // 这里应该从配置文件获取
		const fullUrl = baseImageUrl + iconPath
		console.log('🔗 拼接完整URL:', fullUrl)
		return fullUrl
	}

	// 其他情况，假设是相对于uploads目录的路径
	const baseImageUrl = 'http://8.145.55.161:19000'
	const uploadsUrl = `${baseImageUrl}/uploads/${iconPath}`
	console.log('📁 uploads目录URL:', uploadsUrl)
	return uploadsUrl
}

// 处理图片加载错误
const handleImageError = (event) => {
	console.log('图片加载失败:', event)
	// 图片加载失败时，隐藏图片显示占位符
	const target = event.target
	if (target) {
		target.style.display = 'none'
		// 显示兄弟元素（占位符文本）
		const placeholder = target.parentNode.querySelector('.icon-placeholder')
		if (placeholder) {
			placeholder.style.display = 'block'
		}
	}
}

// 横幅点击事件
const onBannerClick = () => {
	console.log('横幅被点击')
	// 可以跳转到活动页面或者展示更多信息
	uni.showToast({
		title: '欢迎来到海关商品分类',
		icon: 'none',
		duration: 2000
	})
}

// 横幅图片加载错误处理
const onBannerImageError = (event) => {
	console.log('横幅图片加载失败:', event)
	// 图片加载失败时，保持渐变背景显示
	const target = event.target
	if (target) {
		target.style.display = 'none'
	}
}


</script>

<style lang="scss" scoped>
.category-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background: #F5F5F5;
}

.page-header {
	background: #FFFFFF;
	padding: 15px 20px;
	border-bottom: 1px solid #E5E5E5;
	position: sticky;
	top: 0;
	z-index: 100;
}

.page-title {
	font-size: 18px;
	font-weight: 600;
	color: #333333;
}

.main-content {
	flex: 1;
	display: flex;
	overflow: hidden;
	padding-top: 0px;
}

.category-sidebar {
	width: 100px;
	background: #FFFFFF;
	border-right: 1px solid #E5E5E5;
	padding-top: 0px;
}

.category-item {
	padding: 18px 15px;
	text-align: center;
	border-bottom: 1px solid #F8F9FA;
	cursor: pointer;
	position: relative;
	transition: all 0.2s ease;

	&.category-active {
		background: #F0F8FF;
		border-right: 3px solid #007AFF;

		.category-name {
			color: #007AFF;
			font-weight: 600;
		}
	}
}

.category-name {
	font-size: 14px;
	color: #333333;
	line-height: 1.2;
	display: block;
}

.content-area {
	flex: 1;
	background: #F5F5F5;
	padding: 0;
}

.content-header {
	padding: 15px;
	background: #FFFFFF;
	margin-bottom: 1px;
}

.category-banner {
	height: 120px;
	background: linear-gradient(135deg, #007AFF, #5AC8FA);
	border-radius: 8px;
	position: relative;
	overflow: hidden;
	cursor: pointer;
	transition: transform 0.2s ease;

	&:active {
		transform: scale(0.98);
	}
}

.banner-image {
	width: 100%;
	height: 100%;
	position: absolute;
	top: 0;
	left: 0;
	z-index: 1;
}

.banner-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: linear-gradient(135deg, rgba(0, 122, 255, 0.8), rgba(90, 200, 250, 0.6));
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	z-index: 2;
}

.banner-title {
	font-size: 18px;
	font-weight: bold;
	color: #FFFFFF;
	margin-bottom: 4px;
	text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.banner-subtitle {
	font-size: 14px;
	color: rgba(255, 255, 255, 0.9);
	text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.recommend-content,
.category-content {
	padding: 15px;
	background: #FFFFFF;
}

.sub-category-grid {
	display: flex;
	flex-wrap: wrap;
	gap: 0;
	justify-content: flex-start;
	align-items: flex-start;
}

.sub-category-item {
	width: 33.333%;
	padding: 15px 10px;
	display: flex;
	flex-direction: column;
	align-items: center;
	cursor: pointer;
	transition: all 0.2s ease;
	box-sizing: border-box;
	
	&:active {
		transform: scale(0.95);
	}
	
	&.placeholder-item {
		opacity: 0.6;
		pointer-events: none;
	}
}

.sub-category-icon {
	width: 50px;
	height: 50px;
	background: #F0F0F0;
	border-radius: 8px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 8px;
	overflow: hidden;
	border: 1px solid #E0E0E0;
}

.category-image {
	width: 100%;
	height: 100%;
	border-radius: 8px;
	object-fit: cover;
}

.icon-placeholder {
	font-size: 20px;
	color: #CCCCCC;
	display: block;
}

.sub-category-name {
	font-size: 12px;
	color: #333333;
	text-align: center;
	line-height: 1.2;
	max-width: 100%;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.loading-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60px 20px;
	background: #FFFFFF;
}

.loading-spinner {
	width: 30px;
	height: 30px;
	border: 3px solid #F0F0F0;
	border-top: 3px solid #007AFF;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-bottom: 15px;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

.loading-text {
	font-size: 14px;
	color: #999999;
}

.empty-state {
	padding: 20px;
	background: #FFFFFF;
}

/* 交互效果 */
.category-item:active {
	background: #F0F0F0;
}

/* 确保布局在小屏幕上也能正常显示 */
@media screen and (max-width: 375px) {
	.category-sidebar {
		width: 85px;
	}
	
	.category-item {
		padding: 16px 12px;
	}
	
	.category-name {
		font-size: 13px;
	}
	
	.sub-category-icon {
		width: 45px;
		height: 45px;
	}
	
	.icon-placeholder {
		font-size: 18px;
	}
	
	.sub-category-name {
		font-size: 11px;
	}
}
</style>